'use strict';
import axios from 'axios';
import cookies from 'js-cookie';
axios.defaults.timeout = 15000;
// axios.defaults.withCredentials = true;
axios.defaults.xsrfHeaderName = 'x-csrf-token';
axios.defaults.xsrfCookieName = 'csrfToken';

axios.interceptors.request.use(
  config => {
    if (cookies.get('token')&&!config.url.includes('api/v1/user/login')) {
      config.headers.authorization = cookies.get('token')
    }
    return config;
  },
  error => {
    return Promise.error(error);
  }
)

axios.interceptors.response.use(
  response => {
    // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
    // 否则的话抛出错误
    if (response.status === 200) {
      return Promise.resolve(response.data);
    } else {
      return Promise.reject(response);
    }
  },
  error => {
    if (error.response.status === 401) {
      window.location.href = "/login";
      return;
    }
    return Promise.reject(error.response);
  }
);

export default axios;